"""
微信EasyOCR实时监控器 - 优先使用EasyOCR，提高监听及时性
"""

import os
# 解决OpenMP冲突问题
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'

import cv2
import numpy as np
import win32gui
import win32con
import win32api
import win32ui
from PIL import Image, ImageGrab
import threading
import time
import json
import winsound
from datetime import datetime
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
import re
import hashlib
from collections import deque

# 强制导入EasyOCR
try:
    import easyocr
    EASYOCR_AVAILABLE = True
    print("✅ EasyOCR 已成功导入")
except ImportError as e:
    EASYOCR_AVAILABLE = False
    print(f"❌ EasyOCR 导入失败: {e}")
    print("请运行: pip install easyocr")

# 备选OCR
try:
    import pytesseract
    PYTESSERACT_AVAILABLE = True
    print("✅ Pytesseract 已成功导入")
except ImportError:
    PYTESSERACT_AVAILABLE = False
    print("❌ Pytesseract 不可用")

class RealtimeEasyOCRMonitor:
    """实时EasyOCR微信监控器"""
    
    def __init__(self):
        self.wechat_hwnd = None
        self.wechat_pid = None
        self.running = False
        self.messages = []
        self.check_count = 0
        self.sound_enabled = True
        
        # 实时监控配置
        self.config = {
            'check_interval': 0.2,        # 检查间隔：0.2秒（更快响应）
            'easyocr_confidence': 0.3,    # EasyOCR置信度阈值（降低以提高灵敏度）
            'max_message_history': 50,    # 最大消息历史
            'enable_sound': True,         # 启用声音提醒
            'priority_easyocr': True,     # 优先使用EasyOCR
            'save_screenshots': True,     # 保存截图用于调试
            'screenshot_folder': 'screenshots',  # 截图保存文件夹
        }
        
        # 初始化EasyOCR
        self.easyocr_reader = None
        self.easyocr_ready = False
        
        # 消息区域检测参数
        self.message_area_ratio = {
            'x': 0.25,      # 消息区域左边界比例
            'y': 0.1,       # 消息区域上边界比例
            'width': 0.7,   # 消息区域宽度比例
            'height': 0.8   # 消息区域高度比例
        }
        
        # 警报关键词
        self.alert_keywords = ['紧急', '重要', '火急', '赶紧', '立即', '马上', '快']
        
        # GUI回调
        self.gui_callback = None
        
        # 消息历史，用于去重
        self.message_history = set()
        
        # 性能统计
        self.stats = {
            'total_checks': 0,
            'easyocr_calls': 0,
            'pytesseract_calls': 0,
            'successful_detections': 0,
            'start_time': None
        }
        
        # 立即初始化EasyOCR
        self.init_easyocr()
        
        # 创建截图文件夹
        self.create_screenshot_folder()
    
    def create_screenshot_folder(self):
        """创建截图文件夹"""
        try:
            if self.config['save_screenshots']:
                folder = self.config['screenshot_folder']
                if not os.path.exists(folder):
                    os.makedirs(folder)
                    self.log(f"📁 创建截图文件夹: {folder}")
        except Exception as e:
            self.log(f"创建截图文件夹失败: {e}")
    
    def save_screenshot(self, image, prefix="", suffix=""):
        """保存截图"""
        try:
            if not self.config['save_screenshots']:
                return None
                
            timestamp = datetime.now().strftime("%H%M%S")
            filename = f"{prefix}{timestamp}{suffix}.png"
            filepath = os.path.join(self.config['screenshot_folder'], filename)
            
            # 保存图像
            if len(image.shape) == 3:
                # BGR转RGB
                image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
                Image.fromarray(image_rgb).save(filepath)
            else:
                Image.fromarray(image).save(filepath)
            
            return filepath
        except Exception as e:
            self.log(f"保存截图失败: {e}")
            return None
    
    def init_easyocr(self):
        """初始化EasyOCR"""
        if not EASYOCR_AVAILABLE:
            self.log("❌ EasyOCR 不可用，请先安装: pip install easyocr")
            return False
        
        try:
            self.log("🔄 正在初始化EasyOCR引擎...")
            # 创建EasyOCR Reader，支持中文和英文
            self.easyocr_reader = easyocr.Reader(['ch_sim', 'en'], gpu=False, verbose=False)
            self.easyocr_ready = True
            self.log("✅ EasyOCR引擎初始化成功！")
            return True
        except Exception as e:
            self.log(f"❌ EasyOCR初始化失败: {e}")
            self.easyocr_ready = False
            return False
    
    def find_wechat_window(self, silent=False):
        """查找微信窗口"""
        def enum_windows_callback(hwnd, windows):
            if win32gui.IsWindowVisible(hwnd):
                window_title = win32gui.GetWindowText(hwnd)
                class_name = win32gui.GetClassName(hwnd)
                
                if "微信" in window_title and class_name == "WeChatMainWndForPC":
                    try:
                        import win32process
                        _, pid = win32process.GetWindowThreadProcessId(hwnd)
                        windows.append((hwnd, window_title, class_name, pid))
                    except:
                        pass
        
        windows = []
        win32gui.EnumWindows(enum_windows_callback, windows)
        
        if windows:
            old_hwnd = self.wechat_hwnd
            self.wechat_hwnd, title, class_name, self.wechat_pid = windows[0]
            
            # 只在首次找到或窗口句柄变化时输出日志
            if not silent and (old_hwnd != self.wechat_hwnd):
                self.log(f"✅ 找到微信窗口: {title} (句柄: {self.wechat_hwnd}, PID: {self.wechat_pid})")
                
                # 获取窗口位置
                rect = win32gui.GetWindowRect(self.wechat_hwnd)
                self.log(f"📐 窗口位置: {rect}")
            
            return True
        
        if not silent:
            self.log("❌ 未找到微信窗口，请确保微信已启动")
        return False
    
    def capture_wechat_window(self):
        """截取微信窗口"""
        try:
            if not self.wechat_hwnd:
                return None
            
            # 每次都重新检查窗口是否有效
            if not win32gui.IsWindow(self.wechat_hwnd):
                self.log("⚠️ 微信窗口已关闭，重新查找...")
                if not self.find_wechat_window(silent=False):
                    return None
            
            # 重新获取窗口位置（窗口可能被移动或调整大小）
            rect = win32gui.GetWindowRect(self.wechat_hwnd)
            left, top, right, bottom = rect
            
            # 检查窗口是否最小化
            if left < -30000 or top < -30000:
                return None
            
            # 检查窗口大小是否合理
            width = right - left
            height = bottom - top
            if width < 100 or height < 100:
                self.log(f"⚠️ 微信窗口太小: {width}x{height}")
                return None
            
            # 截图
            screenshot = ImageGrab.grab(bbox=(left, top, right, bottom))
            screenshot_array = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
            
            return screenshot_array
            
        except Exception as e:
            self.log(f"截图失败: {e}")
            # 尝试重新查找窗口（静默模式）
            self.find_wechat_window(silent=True)
            return None
    
    def extract_message_area(self, screenshot):
        """提取消息区域"""
        if screenshot is None:
            return None
        
        try:
            height, width = screenshot.shape[:2]
            
            # 计算消息区域
            x = int(width * self.message_area_ratio['x'])
            y = int(height * self.message_area_ratio['y'])
            w = int(width * self.message_area_ratio['width'])
            h = int(height * self.message_area_ratio['height'])
            
            # 提取消息区域
            message_area = screenshot[y:y+h, x:x+w]
            
            return message_area
            
        except Exception as e:
            self.log(f"提取消息区域失败: {e}")
            return None
    
    def extract_text_with_easyocr(self, image_region):
        """使用EasyOCR提取文字"""
        if not self.easyocr_ready:
            return ""
        
        try:
            # 图像预处理
            processed_image = self.preprocess_for_easyocr(image_region)
            
            # 使用EasyOCR识别
            results = self.easyocr_reader.readtext(processed_image)
            
            # 提取文字
            texts = []
            for (bbox, text, confidence) in results:
                if confidence > self.config['easyocr_confidence']:
                    cleaned_text = self.clean_text(text)
                    if cleaned_text:
                        texts.append((cleaned_text, confidence))
            
            # 更新统计
            self.stats['easyocr_calls'] += 1
            
            if texts:
                # 按置信度排序，返回最佳结果
                texts.sort(key=lambda x: x[1], reverse=True)
                return texts[0][0]
            
            return ""
            
        except Exception as e:
            self.log(f"EasyOCR识别失败: {e}")
            return ""
    
    def extract_text_with_pytesseract(self, image_region):
        """使用Pytesseract提取文字（备选方案）"""
        if not PYTESSERACT_AVAILABLE:
            return ""
        
        try:
            # 图像预处理
            processed_image = self.preprocess_for_pytesseract(image_region)
            
            # 使用Pytesseract识别
            text = pytesseract.image_to_string(processed_image, lang='chi_sim+eng')
            
            # 更新统计
            self.stats['pytesseract_calls'] += 1
            
            return self.clean_text(text)
            
        except Exception as e:
            self.log(f"Pytesseract识别失败: {e}")
            return ""
    
    def preprocess_for_easyocr(self, image_region):
        """EasyOCR图像预处理"""
        # 转换为RGB格式
        if len(image_region.shape) == 3:
            rgb_image = cv2.cvtColor(image_region, cv2.COLOR_BGR2RGB)
        else:
            rgb_image = image_region
        
        # 智能缩放
        height, width = rgb_image.shape[:2]
        
        # 如果图像太小，进行放大
        if height < 40 or width < 80:
            scale_factor = max(2, 80 // min(height, width))
            rgb_image = cv2.resize(rgb_image, (width * scale_factor, height * scale_factor), 
                                 interpolation=cv2.INTER_CUBIC)
        
        return rgb_image
    
    def preprocess_for_pytesseract(self, image_region):
        """Pytesseract图像预处理"""
        # 转换为灰度
        gray = cv2.cvtColor(image_region, cv2.COLOR_BGR2GRAY)
        
        # 高斯模糊
        blurred = cv2.GaussianBlur(gray, (3, 3), 0)
        
        # 自适应阈值
        thresh = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, 
                                     cv2.THRESH_BINARY, 11, 2)
        
        # 放大图像
        height, width = thresh.shape
        if height < 40 or width < 80:
            scale_factor = max(2, 80 // min(height, width))
            thresh = cv2.resize(thresh, (width * scale_factor, height * scale_factor), 
                               interpolation=cv2.INTER_CUBIC)
        
        return thresh
    
    def clean_text(self, text):
        """清理提取的文字"""
        if not text:
            return ""
        
        # 去除换行符和多余空格
        text = text.strip().replace('\n', ' ').replace('\r', ' ')
        text = ' '.join(text.split())
        
        # 去除明显的OCR错误
        text = re.sub(r'[|\\\/\[\]{}]', '', text)
        
        # 过滤掉过短的文本
        if len(text) < 1:
            return ""
        
        # 过滤掉只包含特殊字符的文本
        if not any(c.isalnum() or '\u4e00' <= c <= '\u9fff' for c in text):
            return ""
        
        return text
    
    def detect_message_bubbles(self, message_area):
        """检测消息气泡"""
        if message_area is None:
            return []
        
        try:
            # 转换为HSV色彩空间
            hsv = cv2.cvtColor(message_area, cv2.COLOR_BGR2HSV)
            
            # 检测绿色消息气泡（发送的消息）
            lower_green = np.array([35, 30, 30])
            upper_green = np.array([85, 255, 255])
            green_mask = cv2.inRange(hsv, lower_green, upper_green)
            
            # 检测白色消息气泡（接收的消息）
            lower_white = np.array([0, 0, 150])
            upper_white = np.array([180, 50, 255])
            white_mask = cv2.inRange(hsv, lower_white, upper_white)
            
            # 合并掩码
            combined_mask = cv2.bitwise_or(green_mask, white_mask)
            
            # 形态学操作
            kernel = np.ones((3, 3), np.uint8)
            combined_mask = cv2.morphologyEx(combined_mask, cv2.MORPH_CLOSE, kernel)
            combined_mask = cv2.morphologyEx(combined_mask, cv2.MORPH_OPEN, kernel)
            
            # 查找轮廓
            contours, _ = cv2.findContours(combined_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            
            bubbles = []
            for contour in contours:
                area = cv2.contourArea(contour)
                if area > 500:  # 最小面积阈值
                    x, y, w, h = cv2.boundingRect(contour)
                    if w > 50 and h > 20:  # 最小尺寸
                        # 扩展边界
                        padding = 5
                        x_start = max(0, x - padding)
                        y_start = max(0, y - padding)
                        x_end = min(message_area.shape[1], x + w + padding)
                        y_end = min(message_area.shape[0], y + h + padding)
                        
                        bubble = message_area[y_start:y_end, x_start:x_end]
                        bubbles.append(bubble)
            
            return bubbles
            
        except Exception as e:
            self.log(f"检测消息气泡失败: {e}")
            return []
    
    def detect_messages(self, message_area):
        """检测消息"""
        if message_area is None:
            return []
        
        messages = []
        
        try:
            # 检测消息气泡
            bubbles = self.detect_message_bubbles(message_area)
            
            # 如果没有检测到气泡，尝试整个区域
            if not bubbles:
                bubbles = [message_area]
            
            for i, bubble in enumerate(bubbles):
                if bubble.size > 0:
                    text = ""
                    
                    # 优先使用EasyOCR
                    if self.config['priority_easyocr'] and self.easyocr_ready:
                        text = self.extract_text_with_easyocr(bubble)
                    
                    # 如果EasyOCR没有结果，尝试Pytesseract
                    if not text and PYTESSERACT_AVAILABLE:
                        text = self.extract_text_with_pytesseract(bubble)
                    
                    if text and len(text.strip()) > 0:
                        # 保存检测到消息的气泡截图
                        bubble_path = self.save_screenshot(bubble, prefix=f"bubble_{i}_", suffix="_detected")
                        if bubble_path:
                            self.log(f"📸 消息气泡截图已保存: {bubble_path}")
                        
                        # 检查是否为重复消息
                        text_hash = hash(text.strip())
                        
                        if text_hash not in self.message_history:
                            self.message_history.add(text_hash)
                            
                            # 限制历史记录大小
                            if len(self.message_history) > self.config['max_message_history']:
                                # 清理一半的历史记录
                                history_list = list(self.message_history)
                                self.message_history = set(history_list[-25:])
                            
                            # 确定检测方法
                            method = "EasyOCR" if self.easyocr_ready else "Pytesseract"
                            messages.append(f"[{method}] {text}")
            
        except Exception as e:
            self.log(f"消息检测失败: {e}")
        
        return messages
    
    def log(self, message):
        """记录日志"""
        timestamp = datetime.now().strftime("%H:%M:%S")
        log_message = f"[{timestamp}] {message}"
        print(log_message)
        
        if self.gui_callback:
            self.gui_callback(log_message)
    
    def start_monitoring(self):
        """开始监控"""
        if not self.find_wechat_window():
            return False
        
        self.running = True
        self.stats['start_time'] = time.time()
        
        # 显示监控状态
        ocr_status = "EasyOCR" if self.easyocr_ready else "Pytesseract"
        self.log(f"🚀 开始实时监控...")
        self.log(f"🧠 OCR引擎: {ocr_status}")
        self.log(f"⚡ 检查间隔: {self.config['check_interval']}秒")
        self.log(f"🔊 声音提醒: {'开启' if self.config['enable_sound'] else '关闭'}")
        
        # 启动监控线程
        self.monitor_thread = threading.Thread(target=self.monitor_loop, daemon=True)
        self.monitor_thread.start()
        
        return True
    
    def stop_monitoring(self):
        """停止监控"""
        self.running = False
        
        # 显示统计信息
        if self.stats['start_time']:
            duration = time.time() - self.stats['start_time']
            self.log(f"📊 监控统计:")
            self.log(f"   运行时间: {duration:.1f}秒")
            self.log(f"   总检查次数: {self.stats['total_checks']}")
            self.log(f"   EasyOCR调用: {self.stats['easyocr_calls']}")
            self.log(f"   Pytesseract调用: {self.stats['pytesseract_calls']}")
            self.log(f"   成功检测: {self.stats['successful_detections']}")
        
        self.log("⏹ 实时监控已停止")
    
    def monitor_loop(self):
        """监控循环"""
        self.check_count = 0
        
        while self.running:
            try:
                self.check_count += 1
                self.stats['total_checks'] += 1
                
                # 截取微信窗口
                screenshot = self.capture_wechat_window()
                if screenshot is None:
                    time.sleep(self.config['check_interval'])
                    continue
                
                # 保存原始截图（每50次保存一次，避免文件过多）
                if self.check_count % 50 == 0:
                    screenshot_path = self.save_screenshot(screenshot, prefix="wechat_", suffix="_original")
                    if screenshot_path:
                        self.log(f"📸 截图已保存: {screenshot_path}")
                
                # 提取消息区域
                message_area = self.extract_message_area(screenshot)
                if message_area is None:
                    time.sleep(self.config['check_interval'])
                    continue
                
                # 保存消息区域截图（每50次保存一次）
                if self.check_count % 50 == 0:
                    msg_area_path = self.save_screenshot(message_area, prefix="msg_area_", suffix="_extracted")
                    if msg_area_path:
                        self.log(f"📸 消息区域截图已保存: {msg_area_path}")
                
                # 检测消息
                detected_messages = self.detect_messages(message_area)
                
                # 处理检测到的消息
                for message_content in detected_messages:
                    self.process_message(message_content)
                
                # 每50次检查输出一次状态
                if self.check_count % 50 == 0:
                    self.log(f"📊 监控状态: 检查 {self.check_count} 次, 消息 {len(self.messages)} 条")
                
                # 等待下次检查
                time.sleep(self.config['check_interval'])
                
            except Exception as e:
                self.log(f"监控循环出错: {e}")
                time.sleep(1)
    
    def process_message(self, message_content):
        """处理检测到的消息"""
        current_time = datetime.now().strftime("%H:%M:%S")
        
        message = {
            'time': current_time,
            'content': message_content,
            'source': 'EasyOCR实时监控',
            'type': 'realtime_capture'
        }
        
        # 分析消息
        analysis = self.analyze_message(message_content)
        message['analysis'] = analysis
        
        # 添加到消息列表
        self.messages.append(message)
        
        # 更新统计
        self.stats['successful_detections'] += 1
        
        # 保存到文件
        self.save_message_to_file(message)
        
        # 播放提示音
        if self.config['enable_sound']:
            if analysis['alert_level'] == 'high':
                winsound.Beep(1000, 500)  # 高音长响
            else:
                winsound.Beep(800, 200)   # 低音短响
        
        # 记录日志
        self.log(f"🔔 {message_content}")
    
    def analyze_message(self, content):
        """分析消息内容"""
        analysis = {
            'length': len(content),
            'detection_time': datetime.now().isoformat(),
            'keywords': [],
            'alert_level': 'normal',
            'detection_method': 'realtime_capture'
        }
        
        # 检查是否包含警报关键词
        for keyword in self.alert_keywords:
            if keyword in content:
                analysis['alert_level'] = 'high'
                analysis['keywords'].append(keyword)
        
        return analysis
    
    def save_message_to_file(self, message):
        """保存消息到文件"""
        try:
            filename = "wechat_easyocr_realtime_messages.json"
            
            messages = []
            if os.path.exists(filename):
                with open(filename, 'r', encoding='utf-8') as f:
                    messages = json.load(f)
            
            messages.append({
                'timestamp': datetime.now().isoformat(),
                'time': message['time'],
                'content': message['content'],
                'source': message['source'],
                'type': message['type'],
                'analysis': message.get('analysis', {})
            })
            
            # 保持最近200条消息
            if len(messages) > 200:
                messages = messages[-200:]
            
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(messages, f, ensure_ascii=False, indent=2)
                
        except Exception as e:
            self.log(f"保存消息失败: {e}")

class RealtimeEasyOCRGUI:
    """实时EasyOCR监控GUI"""
    
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("微信EasyOCR实时监控器")
        self.root.geometry("900x700")
        self.root.resizable(True, True)
        
        # 确保窗口在前台显示
        self.root.lift()
        self.root.attributes('-topmost', True)
        self.root.after_idle(lambda: self.root.attributes('-topmost', False))
        
        # 先设置UI，再初始化监控器
        self.monitor = None
        self.setup_ui()
        
        # 延迟初始化监控器，避免阻塞GUI显示
        self.root.after(100, self.init_monitor)
    
    def init_monitor(self):
        """初始化监控器"""
        self.add_log("🔄 正在初始化EasyOCR监控器...")
        self.monitor = RealtimeEasyOCRMonitor()
        self.monitor.gui_callback = self.add_log
        self.add_log("✅ 监控器初始化完成")
    
    def setup_ui(self):
        """设置用户界面"""
        # 创建主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 配置网格权重
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        main_frame.columnconfigure(1, weight=1)
        main_frame.rowconfigure(2, weight=1)
        
        # 标题
        title_label = ttk.Label(main_frame, text="微信EasyOCR实时监控器", 
                               font=('Arial', 16, 'bold'))
        title_label.grid(row=0, column=0, columnspan=3, pady=(0, 10))
        
        # 控制按钮框架
        control_frame = ttk.Frame(main_frame)
        control_frame.grid(row=1, column=0, columnspan=3, pady=(0, 10), sticky=(tk.W, tk.E))
        
        # 开始监控按钮
        self.start_button = ttk.Button(control_frame, text="开始监控", 
                                      command=self.start_monitoring)
        self.start_button.pack(side=tk.LEFT, padx=(0, 5))
        
        # 停止监控按钮
        self.stop_button = ttk.Button(control_frame, text="停止监控", 
                                     command=self.stop_monitoring, state=tk.DISABLED)
        self.stop_button.pack(side=tk.LEFT, padx=(0, 5))
        
        # 测试连接按钮
        test_button = ttk.Button(control_frame, text="测试连接", 
                                command=self.test_connection)
        test_button.pack(side=tk.LEFT, padx=(0, 5))
        
        # 清空日志按钮
        clear_button = ttk.Button(control_frame, text="清空日志", 
                                 command=self.clear_log)
        clear_button.pack(side=tk.LEFT, padx=(0, 5))
        
        # 显示统计按钮
        stats_button = ttk.Button(control_frame, text="显示统计", 
                                 command=self.show_stats)
        stats_button.pack(side=tk.LEFT, padx=(0, 5))
        
        # 截图开关
        self.screenshot_var = tk.BooleanVar(value=True)
        screenshot_check = ttk.Checkbutton(control_frame, text="保存截图", 
                                          variable=self.screenshot_var, command=self.toggle_screenshot)
        screenshot_check.pack(side=tk.RIGHT, padx=(0, 10))
        
        # 声音开关
        self.sound_var = tk.BooleanVar(value=True)
        sound_check = ttk.Checkbutton(control_frame, text="声音提醒", 
                                     variable=self.sound_var, command=self.toggle_sound)
        sound_check.pack(side=tk.RIGHT)
        
        # 日志显示区域
        log_frame = ttk.LabelFrame(main_frame, text="监控日志", padding="5")
        log_frame.grid(row=2, column=0, columnspan=3, sticky=(tk.W, tk.E, tk.N, tk.S))
        log_frame.columnconfigure(0, weight=1)
        log_frame.rowconfigure(0, weight=1)
        
        # 日志文本框
        self.log_text = scrolledtext.ScrolledText(log_frame, wrap=tk.WORD, 
                                                 width=80, height=20)
        self.log_text.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 状态栏
        self.status_var = tk.StringVar(value="准备就绪")
        status_bar = ttk.Label(main_frame, textvariable=self.status_var, 
                              relief=tk.SUNKEN, anchor=tk.W)
        status_bar.grid(row=3, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=(10, 0))
        
        # 初始化显示
        self.add_log("微信EasyOCR实时监控器已启动")
        if EASYOCR_AVAILABLE:
            self.add_log("✅ EasyOCR 可用")
        else:
            self.add_log("❌ EasyOCR 不可用")
        
        if PYTESSERACT_AVAILABLE:
            self.add_log("✅ Pytesseract 可用")
        else:
            self.add_log("❌ Pytesseract 不可用")
    
    def add_log(self, message):
        """添加日志"""
        self.log_text.insert(tk.END, message + "\n")
        self.log_text.see(tk.END)
    
    def clear_log(self):
        """清空日志"""
        self.log_text.delete(1.0, tk.END)
    
    def test_connection(self):
        """测试连接"""
        if not self.monitor:
            self.add_log("❌ 监控器未初始化")
            return
            
        if self.monitor.find_wechat_window():
            self.add_log("✅ 微信窗口连接成功")
            self.status_var.set("微信窗口已连接")
        else:
            self.add_log("❌ 微信窗口连接失败")
            self.status_var.set("微信窗口未找到")
    
    def start_monitoring(self):
        """开始监控"""
        if not self.monitor:
            self.add_log("❌ 监控器未初始化，请稍候...")
            return
            
        if self.monitor.start_monitoring():
            self.start_button.config(state=tk.DISABLED)
            self.stop_button.config(state=tk.NORMAL)
            self.status_var.set("监控中...")
            self.add_log("监控已启动")
        else:
            self.add_log("监控启动失败")
    
    def stop_monitoring(self):
        """停止监控"""
        if not self.monitor:
            self.add_log("❌ 监控器未初始化")
            return
            
        self.monitor.stop_monitoring()
        self.start_button.config(state=tk.NORMAL)
        self.stop_button.config(state=tk.DISABLED)
        self.status_var.set("监控已停止")
        self.add_log("监控已停止")
    
    def show_stats(self):
        """显示统计信息"""
        if not self.monitor:
            self.add_log("❌ 监控器未初始化")
            return
            
        stats = self.monitor.stats
        stats_text = f"""
监控统计信息:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
总检查次数: {stats['total_checks']}
EasyOCR调用: {stats['easyocr_calls']}
Pytesseract调用: {stats['pytesseract_calls']}
成功检测: {stats['successful_detections']}
消息总数: {len(self.monitor.messages)}
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
"""
        messagebox.showinfo("统计信息", stats_text)
    
    def toggle_sound(self):
        """切换声音提醒"""
        if not self.monitor:
            self.add_log("❌ 监控器未初始化")
            return
            
        self.monitor.config['enable_sound'] = self.sound_var.get()
        status = "开启" if self.sound_var.get() else "关闭"
        self.add_log(f"声音提醒已{status}")
    
    def toggle_screenshot(self):
        """切换截图保存"""
        if not self.monitor:
            self.add_log("❌ 监控器未初始化")
            return
            
        self.monitor.config['save_screenshots'] = self.screenshot_var.get()
        status = "开启" if self.screenshot_var.get() else "关闭"
        self.add_log(f"截图保存已{status}")
        
        # 如果开启截图，确保文件夹存在
        if self.screenshot_var.get():
            self.monitor.create_screenshot_folder()
    
    def run(self):
        """运行GUI"""
        # 确保窗口显示
        self.root.deiconify()
        self.root.focus_force()
        self.root.mainloop()

def main():
    """主函数"""
    if not EASYOCR_AVAILABLE and not PYTESSERACT_AVAILABLE:
        print("❌ 错误: 没有可用的OCR引擎")
        print("请安装EasyOCR: pip install easyocr")
        print("或安装Pytesseract: pip install pytesseract")
        input("按任意键退出...")
        return
    
    try:
        print("🚀 启动微信EasyOCR实时监控器...")
        print("📱 正在显示GUI界面...")
        
        # 创建并运行GUI
        app = RealtimeEasyOCRGUI()
        print("✅ GUI界面已创建，正在显示...")
        app.run()
        
    except KeyboardInterrupt:
        print("\n程序被用户中断")
    except Exception as e:
        print(f"程序异常: {e}")
        import traceback
        traceback.print_exc()
        input("按任意键退出...")

if __name__ == "__main__":
    main() 